// 2025/3/8
// https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/?envType=study-plan-v2&envId=top-100-liked
// 删除链表的倒数第N个结点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode* cur = head;
            stack<ListNode*> st;
            while(cur != nullptr)
            {
                st.emplace(cur);
                cur = cur->next;
            }
            while(n--)
            {
                if(st.top() == head)
                {
                    ListNode* next = head->next;
                    return next;
                }
                st.pop();
            }
    
            if(!st.empty() && st.top()->next)
                st.top()->next = st.top()->next->next;
            
            return head;
        }
    };